<template>
	<div class="container">
		<view class="styleInput"><u-cell-item :arrow="true" title="提现方式"
				:value="sList[chooseIndex] ? sList[chooseIndex].withdrawTypeName : ''" @click="showPicker = true" />
		</view>
		<template v-if="query.accountType == 1">
			<view class="bank flex-align-center" @click="toDetail">
				<text class="iconfont icon-yinhangka"></text>
				<text class="info">{{ settlement.accountName }} ——
					{{ settlement.bankName }}({{ settlement.accountNo | getTail }})</text>
				<text class="iconfont icon-Downarrow-R iconfont-right"></text>
			</view>
		</template>
		<!-- 提现到支付宝 -->
<!-- 		<template v-if="query.accountType == 2">
			<view class="styleInput" v-if="aliAccount">
				<u-cell-item :arrow="false" :title="'支付宝账号：' + aliAccount" />
				<u-cell-item :arrow="false" :title="'支付宝姓名：' + aliName" />
			</view>
			<view class="styleInput" v-else>
				<u-field v-model="query.aliAccount" label="支付宝账号：" type="text" required :label-width="170"
					placeholder="请输入账号" clearable />
				<u-field v-model="query.aliName" label="支付宝姓名：" type="text" required :label-width="170"
					placeholder="请输入姓名" clearable />
			</view>
		</template> -->
		<view class="w-tip">
			提现时间：早上9:00至晚上22：00，其余时间暂不支持提现
		</view>
		<view class="content">
			<u-radio-group v-model="chooseType" @change="radioGroupChange">
				<view v-for="(item, index) in walletList" :key="index">
					<!--  -->
					<!-- :name="item.serialno" -->
					<view class="item flex" v-if="item.status == 1">
						<u-radio class="radio" shape="circle" :name="item.walletType" active-color="#da7912"></u-radio>
						<view class="account-box flex-column">
							<view class="name">{{ item.walletName }}</view>
							<view class="input-box flex-align-center">
								<!-- <text class="icon">￥</text> -->
								<u-field v-model="query['money' + item.walletType]" :max="item.canWmoney"
									:label-width="0" input-align="left" :border-bottom="false"
									placeholder-style="font-size:28rpx" @click="inputClick(item.walletType)"
									@blur="inputChange(item.walletType)"
									:placeholder="'当前可提现：￥' + item.canWmoney"></u-field>
								<view class="allBtn flex-center" @click="allW(item.walletType)">全部提现</view>
							</view>
						</view>
					</view>
				</view>
			</u-radio-group>
		</view>
		<div class="terminal-top-bottom">
			<div class="terminal-top-bottom-bar flex-space-between">
				<div class="terminal-top-bottom-item-number">
					手续费：
					<span class="red">{{ toFixedNum2(feeTotalNum) }}</span>
					<span class="gray">({{ toFixedNum2(fee) }}+{{ addFee }}元/笔)</span>
				</div>

				<div class="sure-btn flex-center" @click="handleWithdrawal">确认提现</div>
			</div>
		</div>
		<!-- <view class="tips flex-column">
      <text class="red">手续费：123</text>
      <text class="">单笔限额：12322元</text>
      <text class="">单日限制金额：12322元</text>
    </view> -->
		<u-modal ref="uModal" v-model="smsCodeConfirm" @confirm="otherCardWidthdrayQuest" :show-title="false"
			async-close :title-style="{ color: '#000' }" z-index="10" confirm-text="提现" show-cancel-button>
			<view class="tips">提示:接收验证码为本人结算卡的手机号!</view>
			<view class="slot-content">
				<u-field :borderBottom="true" v-model="query.smsCode" label="验证码" placeholder="请填写验证码">
					<u-button size="mini" slot="right" type="success" @click="getCode">{{ codeText }}</u-button>
				</u-field>
				<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
			</view>
		</u-modal>
		<u-picker title="提现方式" v-model="showPicker" mode="selector" :range="sList" range-key="withdrawTypeName"
			confirm-color="#ff5f00" @confirm="onConfirm" @cancel="showBrandPicker = false" />
	</div>
</template>

<script>
	import {
		withdraw,
		otherSettleWithdraw,
		agentEsignOnLine
	} from '_a/earnings';
	import {
		sendNoMeSMS,
		showAgentWallet,
		verifyCardImg
	} from '_a/myInfo';

	export default {
		data() {
			return {
				query: {
					accountType: 1
				},
				walletList: [],
				chooseType: '-1', //选中的钱包类型
				feeTotalNum: 0, //总手续费
				fee: 0, // //提现手续费
				addFee: 0, //每笔提现手续费
				sList: [
					// {
					// 	withdrawTypeName: '支付宝',
					// 	value: '2'
					// },
					{
						withdrawTypeName: '银行卡',
						value: '1'
					}

				],
				showPicker: false,
				aliAccount: '',
				aliName: '',
				chooseIndex: 0, //提现类型下标
				settlement: {},
				smsCodeConfirm: false,
				codeText: '',
				code: '',
				needUploadIdcard: false //是否需要上传身份证
			};
		},
		filters: {
			getTail(v) {
				if (v) {
					return v.slice(-4);
				}
			}
		},
		computed: {
			user() {
				return this.$store.getters.user || {};
			},
			withdrawRate() {
				return this.$store.getters.userInfo.withdrawRate || [];
			}
		},
		// 下拉刷新
		async onPullDownRefresh() {
			this.$store.dispatch('getUserDetail').then(res => {
				uni.stopPullDownRefresh();
				this.$tip.toast('刷新成功!', 'success', 500);
			});
		},
		async onLoad() {
			// let data = await showAgentWallet()
			// if (data.code == 200) {
			// 	if (data.data.showCard && data.data.showZfb) {
			// 		this.sList = [{
			// 				withdrawTypeName: '银行卡',
			// 				value: '1'
			// 			},
			// 			{
			// 				withdrawTypeName: '支付宝',
			// 				value: '2'
			// 			}
			// 		]
			// 	} else if (data.data.showZfb) {
			// 		this.sList = [{
			// 			withdrawTypeName: '支付宝',
			// 			value: '2'
			// 		}]
			// 		this.query.accountType = 2
			// 	} else if (data.data.showCard) {
			// 		this.sList = [{
			// 			withdrawTypeName: '银行卡',
			// 			value: '1'
			// 		}]
			// 	}
			// }
			// this.checkIdCardIsUpload()
			this.$store.dispatch('getUserDetail').then(() => {
				this.getData();
			});
			uni.$on('chooseCard', this.chooseCard);
		},
		onUnload() {
			uni.$off('chooseCard', this.chooseCard);
		},
		methods: {
			async checkIdCardIsUpload() {
				return new Promise(async (resolve, reject) => {
					let accountNo = this.$store.getters.userInfo.settlement.accountNo
						console.log(this.query.accountType);
					// 银行卡直接跳过
					if(this.query.accountType==2){
						resolve()
						return
					}
					if (accountNo) {
						let data = await verifyCardImg({
							accountNo: accountNo
						})
						if (data.code !== 200) {
							reject()
							// this.needUploadIdcard = true
							this.$tip.modal({
								title: '提示',
								content: '您需要补充身份证照片!',
								showCancel: false,
								confirmText: '立即前往'

							}).then(res => {
								this.$nav.push({
									path: "/pages/myInfo/settlementAccount/index"
								})
							});
						} else {
							resolve()
						}
					} else {
						reject()
					}
				})

			},
			codeChange(text) {
				this.codeText = text;
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					});
					sendNoMeSMS().then(res => {
						uni.hideLoading();
						// 通知验证码组件内部开始倒计时
						if (res.code === 200) {
							this.$refs.uCode.start();
						}
					});
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			chooseCard(item) {
				this.settlement = item;
			},
			toDetail() {
				this.$nav.push({
					path: '/pages/myInfo/settlementAccount/index',
					query: {
						type: 'withdraw'
					}
				});
			},
			onConfirm(e) {
				console.log(e);
				this.query.accountType = this.sList[e[0]].value;
				this.chooseIndex = e[0];
			},
			getData() {
				let list = JSON.parse(JSON.stringify(this.$store.getters.userInfo.wallet));
				this.walletList = list.map(item => {
					item.canWmoney = this.toFixedNum2(item.usableAmount - Math.abs(item.freezeAmount) - Math.abs(
						item.transitAmount));
					if (item.canWmoney < 0) {
						item.canWmoney = '0.00';
					}
					return item;
				});
				this.walletList = this.walletList.filter(item => {
					return item.walletType != 6;
				});
				this.aliAccount = this.$store.getters.user.aliAccount;
				this.aliName = this.$store.getters.user.aliName;
				if (this.aliAccount) {
					this.query.aliAccount = this.aliAccount;
					this.query.aliName = this.aliName;
				}
				this.settlement = this.$store.getters.userInfo.settlement || {};
			},
			getFee() {
				let item = this.withdrawRate.find(item => item.walletType == this.chooseType);
				if (item) {
					this.feeTotalNum = this.$data.query['money' + this.chooseType] * (item.rate / 100) + item.addFee;
					this.fee = this.$data.query['money' + this.chooseType] * (item.rate / 100);
					this.addFee = item.addFee;
				}
			},
			allW(type) {
				this.clearAllMoney();
				this.chooseType = type;
				let item = this.walletList.find(item => item.walletType == type);
				if (item) {
					this.$data.query['money' + type] = item.canWmoney;
				}
				this.getFee();
			},
			clearAllMoney() {
				let data = {
					aliAccount: this.query.aliAccount,
					aliName: this.query.aliName,
					accountType: this.query.accountType
				};
				this.query = data;
			},
			inputChange(type) {
				let item = this.walletList.find(item => item.walletType == type);
				if (this.$data.query['money' + type] > Number(item.canWmoney)) {
					this.$data.query['money' + type] = item.canWmoney;
					this.$forceUpdate();
				}
				this.getFee();
			},
			inputClick(type) {
				this.clearAllMoney();
				this.chooseType = type;
			},
			radioGroupChange(v) {
				this.clearAllMoney();
			},
			otherCardWidthdrayQuest() {
				if (!this.query.smsCode) {
					this.$refs.uModal.clearLoading();
					return this.$tip.toast('请输入验证码!');
				}
				let params = {
					amount: this.$data.query['money' + this.chooseType],
					walletType: this.chooseType,
					accountType: this.query.accountType == 1 ? this.settlement.accountType : this.query
						.accountType //0: 0 对私 1 对公 2 支付宝
				};
				params.accountNo = this.settlement.accountNo;
				params.smsCode = this.query.smsCode;
				otherSettleWithdraw(params).then(res => {
					this.$refs.uModal.clearLoading();
					this.$tip.loaded();
					if (res.code == 200) {
						this.smsCodeConfirm = false;
						this.query.amount = '';
						this.$store.dispatch('getUserDetail').then(() => {
							this.getData();
						});
					}
					// this.$toast.success("提现成功!");
					this.$tip.modal({
						content: res.msg,
						showCancel: false
					});
				});
			},
			// 提现请求
			async widthdrawQuest() {
				this.$tip.loading('提现中....');
				let params = {
					amount: this.$data.query['money' + this.chooseType],
					walletType: this.chooseType,
					accountType: this.query.accountType == 1 ? this.settlement.accountType : this.query.accountType, //0: 0 对私 1 对公 2 支付宝
					toSelfCard: this.settlement.isSelf,//提现到本人还是他人结算卡
					currentPath: window.location.href,//当前页面路径
				};
				if (this.query.accountType == 2) {
					params.aliAccount = this.query.aliAccount;
					params.aliName = this.query.aliName;
				}
				//发起耕耘签约
				let resLine = await agentEsignOnLine(params); 
				if (resLine.code == 200 && resLine.data.signUrl) {
					this.$tip.loaded();
					uni.navigateTo({
						url: '/pages/earnings/esignOnLineView?url=' + resLine.data.signUrl,
					})
					return;
				}else if(resLine.code != 200){
					this.$tip.loaded();
					return this.$tip.modal({
						title: '提示',
						content: resLine.msg,
						showCancel: false
					})
				}
				//对私而且选了提现到其他银行卡
				console.log(this.query.accountType, this.settlement.isSelf);
				if (this.query.accountType == 1 && this.settlement.isSelf == 0) {
					this.$tip.loaded();
					// 短信二次确认
					this.query.smsCode = '';
					this.smsCodeConfirm = true;
				} else {
					// 提现到自己卡
					withdraw(params).then(res => {
						this.$tip.loaded();
						if (res.code == 200) {
							this.query.amount = '';
							this.$store.dispatch('getUserDetail').then(() => {
								this.getData();
							});
						}
						// this.$toast.success("提现成功!");
						this.$tip.modal({
							content: res.msg,
							showCancel: false
						});
					});
				}
			},
			handleWithdrawal() {
				// return;
				// console.log(this.$data.query["money" + this.chooseType]);
				// if (this.needUploadIdcard) {
				// 	return this.$tip.modal({
				// 		title: '提示',
				// 		content: '您需要补充身份证照片!',
				// 		showCancel: false,
				// 		confirmText: '立即前往'
				// 	}).then(res => {
				// 		this.$nav.push({
				// 			path: "/pages/earnings/uploadIdCard"
				// 		})
				// 	});
				// }
				this.checkIdCardIsUpload().then(() => {
					if (this.chooseType < 0) {
						return this.$tip.toast('请选择提现账户!');
					}
				
					if (this.$data.query['money' + this.chooseType] <= 0 || !this.$data.query['money' + this
							.chooseType]) {
						return this.$tip.toast('请输入提现金额!');
					}
					if (this.fee < 0 && !this.fee) {
						return this.$tip.modal({
							content: '请联系运营人员配置手续费!',
							showCancel: false
						});
					}
					switch (Number(this.query.accountType)) {
						case 1:
							if (!this.settlement.accountName) {
								return this.$tip
									.modal({
										content: '请先绑卡!',
										showCancel: false
									})
									.then(res => {
										this.toBindCard();
									});
								return;
							}
							break;
						case 2:
							if (!this.query.aliAccount) {
								return this.$tip.toast('请输入支付宝信息');
							}
							break;
						default:
							break;
					}
					this.widthdrawQuest();
				})

			}
		}
	};
</script>
<style scoped lang="scss">
	.container {
		padding-top: R(20);
		padding-bottom: R(120);
	}

	.bank {
		padding: R(30) R(30);
		background: #fff;
		font-size: R(26);
		margin-bottom: R(12);

		.icon-yinhangka {
			font-size: R(42);
		}

		.info {
			margin-left: R(20);
		}

		.icon-Downarrow-R {
			margin-left: auto;
			color: #cfcbc9;
		}
	}

	.content {
		background: #fff;
		padding: R(18) 0 R(30);

		.item {
			border-bottom: 1px solid #eee;
			padding: R(20) R(30);

			.radio {
				// display: flex;
				// align-items: center;
			}

			.account-box {

				//   margin-left: R(30);
				.name {
					// font-size: $uni-font-size-lg;
					margin-bottom: R(20);
				}

				.input-box {
					.u-field {
						padding: 0;

						/deep/input {
							font-size: R(42);
						}
					}

					.icon {
						font-size: $uni-font-size-title;
					}

					.allBtn {
						margin-left: auto;
						font-size: R(26);
						color: $themeColor;
						white-space: nowrap;
					}
				}
			}
		}
	}

	.tips {
		margin-top: R(18);
		background: #fff;
		font-size: R(24);
		color: #a09d9b;
		padding: R(20) R(30);

		.red {
			color: #f74e30;
		}
	}

	.w-tip {
		color: #f74e30;
		font-size: R(24);
		background: #fff;
		padding: R(20) R(20) R(0);
	}

	.terminal-top-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 100;
		width: 100%;
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #fff;
		-webkit-user-select: none;
		user-select: none;
		box-shadow: 0px R(5) R(21) R(3) rgba(13, 133, 244, 0.14);

		.terminal-top-bottom-bar {
			height: R(104);
			font-size: R(28);
			padding-left: R(30);

			.red {
				color: red;
				font-size: R(34);
			}

			.gray {
				color: #999;
			}

			.add-all {
				font-size: R(28);
				height: R(60);
				width: R(150);
			}

			.sure-btn {
				height: 100%;
				width: R(200);
				background: $box-linear-bg;
				font-size: R(30);
				color: #fff;
			}
		}
	}

	.styleInput {
		background: #fff;
		margin-bottom: R(12);
	}

	.tips {
		color: #f74e30;
		font-size: R(25);
		margin-top: R(30);
		text-align: center;
	}

	.slot-content {
		font-size: 28rpx;
		color: $u-content-color;
		padding: 30rpx 20rpx;
	}
</style>